package com.xhtt.modules.task.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.Query;
import com.xhtt.modules.msg.entity.MsgInfo;
import com.xhtt.modules.msg.entity.MsgUser;
import com.xhtt.modules.msg.service.MsgInfoService;
import com.xhtt.modules.msg.service.MsgUserService;
import com.xhtt.modules.sys.entity.SysDeptEntity;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.sys.service.SysDeptService;
import com.xhtt.modules.sys.service.SysUserService;
import com.xhtt.modules.task.dao.TaskAllMapper;
import com.xhtt.modules.task.entity.*;
import com.xhtt.modules.task.model.alltask.*;
import com.xhtt.modules.task.model.msg.ShiftsModel;
import com.xhtt.modules.task.model.msg.ShiftsToUserModel;
import com.xhtt.modules.task.model.report.TaskForRankingModel;
import com.xhtt.modules.task.model.report.TaskForSelfModel;
import com.xhtt.modules.task.model.report.TaskForTeamModel;
import com.xhtt.modules.task.model.report.TaskForTeamUserModel;
import com.xhtt.modules.task.model.ship.WorkUserModel;
import com.xhtt.modules.task.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author feipc
 * @since 2019-02-27
 */
@Service
public class TaskAllServiceImpl extends ServiceImpl<TaskAllMapper, TaskAllModel> implements TaskAllService {
    @Autowired
    private TaskOperTaskService operTaskService;
    @Autowired
    private TaskPotTaskService potTaskService;
    @Autowired
    private TaskServiceTaskService serviceTaskService;
    @Autowired
    private TaskShipTaskService shipTaskService;
    @Autowired
    private TaskOperTaskUserService operTaskUserService;
    @Autowired
    private TaskPotTaskUserService potTaskUserService;
    @Autowired
    private TaskServiceTaskUserService serviceTaskUserService;
    @Autowired
    private TaskShipTaskUserService shipTaskUserService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private MsgInfoService msgInfoService;
    @Autowired
    private MsgUserService msgUserService;

    @Override
    public int allTaskCount(SysUserEntity user, Integer status) {
        Integer userId = user.getUserId().intValue();//先只查自己的任务，其他业务豆面再说呗
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        Map<String, Object> params = new HashMap<>();
        params.put("userIds", userIds);
        params.put("status", status);
        if (status.intValue() == 9) {
            params.remove("userIds");
            params.put("confirmUserId", userId);//确认任务的时候要根据确认人来查询
        }
        int count = baseMapper.allTaskCount(params);
        return count;
    }

    @Override
    public List<TaskAllModel> allTaskList(SysUserEntity user, Integer status) {
        Integer userId = user.getUserId().intValue();//先只查自己的任务，其他业务豆面再说呗
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        Map<String, Object> params = new HashMap<>();
        params.put("userIds", userIds);
        params.put("status", status);
        if (status.intValue() == 9) {
            params.remove("userIds");
            params.put("confirmUserId", userId);//确认任务的时候要根据确认人来查询
        }
        List<TaskAllModel> list = baseMapper.allTaskList(params);
        list.forEach(taskAllModel -> {
            if (StringUtils.isNotEmpty(taskAllModel.getUserAssist())) {
                taskAllModel.setUserAssistModelList(JSON.parseArray(taskAllModel.getUserAssist(), WorkUserModel.class));
            }
        });
        return list;
    }

    @Override
    @Transactional
    public void changeShifts(SysUserEntity user, SuperTaskUser tu) {
        Integer selfId = user.getUserId().intValue();
        //查询自己没完成的任务 4大类任务
        List<TaskOperTask> operTasks = operTaskService.shiftsList(selfId);
        List<TaskPotTask> potTasks = potTaskService.shiftsList(selfId);
        List<TaskServiceTask> serviceTasks = serviceTaskService.shiftsList(selfId);
        List<TaskShipTask> shipTasks = shipTaskService.shiftsList(selfId);
        if (null == tu.getTargetUserId()) {
            // 发给组长
            SysUserEntity leader = sysUserService.getTeamLeaderByUser(user.getUserId().intValue());
            if (null == leader) {
                throw new RRException("没有组长");
            }
            Set<Integer> targetUserIds = new HashSet<>();
            targetUserIds.add(leader.getUserId().intValue());
            if (CollectionUtils.isNotEmpty(operTasks)) {
                List<MsgInfo> msgList = new ArrayList<>();
                for (TaskOperTask tk : operTasks) {
                    tk.setUserMainId(0);//先设置个不存在的人
                    String detail = tk.getMainTaskName() + "#" + tk.getName();
                    ShiftsToUserModel model = new ShiftsToUserModel(detail, user.getName(), "oper", tk.getId(), null);
                    MsgInfo msg = new MsgInfo("交接班信息", "计划任务-分配组", "计划任务", JSON.toJSONString(model));
                    msg.setUserIdList(targetUserIds);
                    msgList.add(msg);
                }
                msgInfoService.saveMsgBatch(msgList);
                operTaskService.updateBatchById(operTasks);
                operTaskUserService.saveShiftDetail(user, operTasks);
            }
            if (CollectionUtils.isNotEmpty(potTasks)) {
                List<MsgInfo> msgList = new ArrayList<>();
                for (TaskPotTask tk : potTasks) {
                    tk.setUserMainId(0);//先设置个不存在的人
                    String detail = tk.getMainTaskName() + "#" + tk.getName();
                    ShiftsToUserModel model = new ShiftsToUserModel(detail, user.getName(), "pot", tk.getId(), null);
                    MsgInfo msg = new MsgInfo("交接班信息", "计划任务-分配组", "计划任务", JSON.toJSONString(model));
                    msg.setUserIdList(targetUserIds);
                    msgList.add(msg);
                }
                msgInfoService.saveMsgBatch(msgList);
                potTaskService.updateBatchById(potTasks);
                potTaskUserService.saveShiftDetail(user, potTasks);
            }
            if (CollectionUtils.isNotEmpty(serviceTasks)) {
                List<MsgInfo> msgList = new ArrayList<>();
                for (TaskServiceTask tk : serviceTasks) {
                    tk.setUserMainId(0);//先设置个不存在的人
                    String detail = tk.getMainTaskName() + "#" + tk.getName();
                    ShiftsToUserModel model = new ShiftsToUserModel(detail, user.getName(), "service", tk.getId(), null);
                    MsgInfo msg = new MsgInfo("交接班信息", "计划任务-分配组", "计划任务", JSON.toJSONString(model));
                    msg.setUserIdList(targetUserIds);
                    msgList.add(msg);
                }
                msgInfoService.saveMsgBatch(msgList);
                serviceTaskService.updateBatchById(serviceTasks);
                serviceTaskUserService.saveShiftDetail(user, serviceTasks);
            }
            if (CollectionUtils.isNotEmpty(shipTasks)) {
                List<MsgInfo> msgList = new ArrayList<>();
                for (TaskShipTask tk : shipTasks) {
                    tk.setUserMainId(0);//先设置个不存在的人
                    String detail = tk.getMainTaskName() + "#" + tk.getName();
                    ShiftsToUserModel model = new ShiftsToUserModel(detail, user.getName(), "ship", tk.getId(), null);
                    MsgInfo msg = new MsgInfo("交接班信息", "计划任务-分配组", "计划任务", JSON.toJSONString(model));
                    msg.setUserIdList(targetUserIds);
                    msgList.add(msg);
                }
                msgInfoService.saveMsgBatch(msgList);
                shipTaskService.updateBatchById(shipTasks);
                shipTaskUserService.saveShiftDetail(user, shipTasks);
            }
        } else {
            List<String> details = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(operTasks)) {
                for (TaskOperTask tk : operTasks) {
                    tk.setUserMainId(tu.getTargetUserId());
                    details.add(tk.getMainTaskName() + "#" + tk.getName());
                }
                operTaskService.updateBatchById(operTasks);
                operTaskUserService.saveShiftDetail(selfId, tu, operTasks);
            }
            if (CollectionUtils.isNotEmpty(potTasks)) {
                for (TaskPotTask tk : potTasks) {
                    tk.setUserMainId(tu.getTargetUserId());
                    details.add(tk.getMainTaskName() + "#" + tk.getName());
                }
                potTaskService.updateBatchById(potTasks);
                potTaskUserService.saveShiftDetail(selfId, tu, potTasks);
            }
            if (CollectionUtils.isNotEmpty(serviceTasks)) {
                for (TaskServiceTask tk : serviceTasks) {
                    tk.setUserMainId(tu.getTargetUserId());
                    details.add(tk.getMainTaskName() + "#" + tk.getName());
                }
                serviceTaskService.updateBatchById(serviceTasks);
                serviceTaskUserService.saveShiftDetail(selfId, tu, serviceTasks);
            }
            if (CollectionUtils.isNotEmpty(shipTasks)) {
                for (TaskShipTask tk : shipTasks) {
                    tk.setUserMainId(tu.getTargetUserId());
                    details.add(tk.getMainTaskName() + "#" + tk.getName());
                }
                shipTaskService.updateBatchById(shipTasks);
                shipTaskUserService.saveShiftDetail(selfId, tu, shipTasks);
            }
            //发消息
            taskExecutor.submit(() -> {
                if (CollectionUtils.isNotEmpty(details)) {
                    ShiftsModel model = new ShiftsModel();
                    model.setSelfUser(user.getName());
                    model.setTargetUser(tu.getUserName());
                    model.setDetail(String.join("、", details));

                    List<Integer> userIds = new ArrayList<>();
                    userIds.add(tu.getTargetUserId());
                    MsgInfo msg = new MsgInfo("交接班信息", "计划任务", "计划任务", JSON.toJSONString(model));
                    msgUserService.insertBatch(msg, userIds);
                }
            });
        }
    }

    @Override
    public PageUtils corePlanList(Map<String, Object> params) {
        Page<TaskPlanAllModel> page = new Query<TaskPlanAllModel>(params).getPage();
        List<TaskPlanAllModel> list = baseMapper.corePlanList(page, params);
        //设置子任务信息
        for (TaskPlanAllModel model : list) {
            String plan = model.getPlan();
            Integer planId = model.getPlanId();//
            Integer planType = model.getPlanType();//plan任务类型 比如 1装船2卸船 1维修需求 2维修确认
            if ("oper".equals(plan)) {
                List<TaskOperTask> subTasks = operTaskService.list(new LambdaQueryWrapper<TaskOperTask>().eq(TaskOperTask::getOperPlanId, planId).select(TaskOperTask::getId, TaskOperTask::getType, TaskOperTask::getExecTeamId, TaskOperTask::getUserMainId, TaskOperTask::getName, TaskOperTask::getStatus, TaskOperTask::getType));
                List<SubTaskModel> stms = new ArrayList<>();
                SubTaskModel stm;
                List<TeamUserModel> tums = new ArrayList<>();
                TeamUserModel tum;
                int percent = 0;
                for (TaskOperTask subTask : subTasks) {
                    Integer subTaskStatus = subTask.getStatus();
                    stm = new SubTaskModel(subTask.getId(), subTask.getType(), subTask.getName(), (null == subTaskStatus || subTaskStatus.intValue() < 9) ? 0 : 1);
                    stms.add(stm);
                    //狗日的需求 算他妈的完成比例 fffuuuuucccccccckkkkkk
                    Integer subTaskType = subTask.getType();
                    Integer pt = baseMapper.getSubTaskPercent(plan, planType, subTaskType);
                    if (null != subTaskStatus && subTaskStatus.intValue() >= 9) {
                        if (null != pt)//正常任务
                        {
                            percent = percent + pt.intValue();
                        } else//临时任务
                        {
                            percent = 100;
                        }

                    }

                    //设置人员 组信息
                    tum = new TeamUserModel();
                    if (null != subTask.getExecTeamId()) {
                        SysDeptEntity dept = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptEntity>().eq(SysDeptEntity::getDeptId, subTask.getExecTeamId()).select(SysDeptEntity::getDeptId, SysDeptEntity::getName));
                        if (null != dept) {
                            tum.setTeamName(dept.getName());
                        }
                    }
                    if (null != subTask.getUserMainId()) {
                        SysUserEntity user = sysUserService.getOne(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getUserId, subTask.getUserMainId()).select(SysUserEntity::getUserId, SysUserEntity::getName));
                        if (null != user) {
                            tum.setUserName(user.getName());
                        }
                    }
                    tums.add(tum);
                }
                //因为可能删除基础任务，所以看一下是不是所有子任务都完成了，是的话就进度改成100%
                subTasks.removeIf(taskOperTask -> (null != taskOperTask.getStatus() && taskOperTask.getStatus() >= 9));
                if (subTasks.size() == 0) {
                    model.setPercent(100);
                } else {
                    model.setPercent(percent);
                }
                model.setSubTaskModelList(stms);
                model.setUserModelList(tums);
            } else if ("pot".equals(plan)) {
                List<TaskPotTask> subTasks = potTaskService.list(new LambdaQueryWrapper<TaskPotTask>().eq(TaskPotTask::getPotPlanId, planId).select(TaskPotTask::getId, TaskPotTask::getType, TaskPotTask::getExecTeamId, TaskPotTask::getUserMainId, TaskPotTask::getName, TaskPotTask::getStatus, TaskPotTask::getType));
                List<SubTaskModel> stms = new ArrayList<>();
                SubTaskModel stm;
                List<TeamUserModel> tums = new ArrayList<>();
                TeamUserModel tum;
                int percent = 0;
                //先看看有个软管连接
                Long hoseTaskCount = subTasks.stream().filter(t -> t.getType().intValue() == 1).count();
                for (TaskPotTask subTask : subTasks) {
                    String subTaskName = subTask.getName();
                    Integer subTaskStatus = subTask.getStatus();
                    Integer subTaskType = subTask.getType();
                    Integer teamId = subTask.getExecTeamId();
                    Integer userId = subTask.getUserMainId();

                    stm = new SubTaskModel(subTask.getId(), subTask.getType(), subTaskName, (null == subTaskStatus || subTaskStatus.intValue() < 9) ? 0 : 1);
                    stms.add(stm);

                    //设置人员 组信息
                    tum = new TeamUserModel();
                    if (null != teamId) {
                        SysDeptEntity dept = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptEntity>().eq(SysDeptEntity::getDeptId, teamId).select(SysDeptEntity::getDeptId, SysDeptEntity::getName));
                        if (null != dept) {
                            tum.setTeamName(dept.getName());
                        }
                    }
                    if (null != userId) {
                        SysUserEntity user = sysUserService.getOne(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getUserId, userId).select(SysUserEntity::getUserId, SysUserEntity::getName));
                        if (null != user) {
                            tum.setUserName(user.getName());
                        }
                    }
                    tums.add(tum);
                    //狗日的需求 算他妈的完成比例 fffuuuuucccccccckkkkkk
                    Integer pt = baseMapper.getSubTaskPercent(plan, planType, subTaskType);
                    //软管连接最恶心，还要全都完成才算完成
                    if (subTaskType.intValue() == 1 && null != subTaskStatus && subTaskStatus.intValue() >= 9 && hoseTaskCount == 1 && null != pt) {
                        percent = percent + pt.intValue();
                    } else if (subTaskType.intValue() == 1 && null != subTaskStatus && subTaskStatus.intValue() >= 9 && hoseTaskCount > 1) {
                        hoseTaskCount--;
                        continue;
                    } else if (null != subTaskStatus && subTaskStatus.intValue() >= 9 && null != pt) {
                        percent = percent + pt.intValue();
                    }
                }
                //因为可能删除基础任务，所以看一下是不是所有子任务都完成了，是的话就进度改成100%
                subTasks.removeIf(taskOperTask -> (null != taskOperTask.getStatus() && taskOperTask.getStatus() >= 9));
                if (subTasks.size() == 0) {
                    model.setPercent(100);
                } else {
                    model.setPercent(percent);
                }
                model.setSubTaskModelList(stms);
                model.setUserModelList(tums);
            } else if ("service".equals(plan)) {
                List<TaskServiceTask> subTasks = serviceTaskService.list(new LambdaQueryWrapper<TaskServiceTask>().eq(TaskServiceTask::getServicePlanId, planId).select(TaskServiceTask::getId, TaskServiceTask::getType, TaskServiceTask::getExecTeamId, TaskServiceTask::getUserMainId, TaskServiceTask::getName, TaskServiceTask::getStatus, TaskServiceTask::getType));
                List<SubTaskModel> stms = new ArrayList<>();
                SubTaskModel stm;
                List<TeamUserModel> tums = new ArrayList<>();
                TeamUserModel tum;
                int percent = 0;
                for (TaskServiceTask subTask : subTasks) {
                    Integer subTaskStatus = subTask.getStatus();
                    String subTaskName = subTask.getName();
                    Integer subTaskType = subTask.getType();
                    Integer teamId = subTask.getExecTeamId();
                    Integer userId = subTask.getUserMainId();

                    stm = new SubTaskModel(subTask.getId(), subTask.getType(), subTaskName, (null == subTaskStatus || subTaskStatus.intValue() < 9) ? 0 : 1);
                    stms.add(stm);
                    //狗日的需求 算他妈的完成比例 fffuuuuucccccccckkkkkk
                    Integer pt = baseMapper.getSubTaskPercent(plan, planType, subTaskType);
                    if (null != subTaskStatus && subTaskStatus.intValue() >= 9) {
                        if (null != pt)//正常任务
                        {
                            percent = percent + pt.intValue();
                        } else//临时任务
                        {
                            percent = 100;
                        }
                    }

                    //设置人员 组信息
                    tum = new TeamUserModel();
                    if (null != teamId) {
                        SysDeptEntity dept = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptEntity>().eq(SysDeptEntity::getDeptId, teamId).select(SysDeptEntity::getDeptId, SysDeptEntity::getName));
                        if (null != dept) {
                            tum.setTeamName(dept.getName());
                        }
                    }
                    if (null != userId) {
                        SysUserEntity user = sysUserService.getOne(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getUserId, userId).select(SysUserEntity::getUserId, SysUserEntity::getName));
                        if (null != user) {
                            tum.setUserName(user.getName());
                        }
                    }
                    tums.add(tum);
                }
                //因为可能删除基础任务，所以看一下是不是所有子任务都完成了，是的话就进度改成100%
                subTasks.removeIf(taskOperTask -> (null != taskOperTask.getStatus() && taskOperTask.getStatus() >= 9));
                if (subTasks.size() == 0) {
                    model.setPercent(100);
                } else {
                    model.setPercent(percent);
                }
                model.setSubTaskModelList(stms);
                model.setUserModelList(tums);
            } else if ("ship".equals(plan)) {
                List<TaskShipTask> subTasks = shipTaskService.list(new LambdaQueryWrapper<TaskShipTask>().eq(TaskShipTask::getShipPlanId, planId).select(TaskShipTask::getId, TaskShipTask::getType, TaskShipTask::getExecTeamId, TaskShipTask::getUserMainId, TaskShipTask::getName, TaskShipTask::getStatus, TaskShipTask::getType));
                List<SubTaskModel> stms = new ArrayList<>();
                SubTaskModel stm;
                List<TeamUserModel> tums = new ArrayList<>();
                TeamUserModel tum;
                int percent = 0;
                //先看看有几个个软管连接 或 打尺取样
                Long hoseTaskCount = subTasks.stream().filter(t -> t.getType().intValue() == 1).count();
                Long dcqyTaskCount = subTasks.stream().filter(t -> t.getType().intValue() == 5).count();
                for (TaskShipTask subTask : subTasks) {
                    String subTaskName = subTask.getName();
                    Integer subTaskStatus = subTask.getStatus();
                    Integer subTaskType = subTask.getType();
                    Integer userId = subTask.getUserMainId();
                    Integer teamId = subTask.getExecTeamId();

                    stm = new SubTaskModel(subTask.getId(), subTask.getType(), subTaskName, (null == subTaskStatus || subTaskStatus.intValue() < 9) ? 0 : 1);
                    stms.add(stm);

                    //设置人员 组信息
                    tum = new TeamUserModel();
                    if (null != teamId) {
                        SysDeptEntity dept = sysDeptService.getOne(new LambdaQueryWrapper<SysDeptEntity>().eq(SysDeptEntity::getDeptId, teamId).select(SysDeptEntity::getDeptId, SysDeptEntity::getName));
                        if (null != dept) {
                            tum.setTeamName(dept.getName());
                        }
                    }
                    if (null != userId) {
                        SysUserEntity user = sysUserService.getOne(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getUserId, userId).select(SysUserEntity::getUserId, SysUserEntity::getName));
                        if (null != user) {
                            tum.setUserName(user.getName());
                        }
                    }
                    tums.add(tum);
                    //狗日的需求 算他妈的完成比例 fffuuuuucccccccckkkkkk
                    Integer pt = baseMapper.getSubTaskPercent(plan, planType, subTaskType);
                    //软管连接 打尺取样最恶心，还要全都完成才算完成
                    if (subTaskType.intValue() == 1 && null != subTaskStatus && subTaskStatus.intValue() >= 9 && hoseTaskCount == 1 && null != pt) {
                        percent = percent + pt.intValue();
                    } else if (subTaskType.intValue() == 1 && null != subTaskStatus && subTaskStatus.intValue() >= 9 && hoseTaskCount > 1) {
                        hoseTaskCount = hoseTaskCount - 1;
                        continue;
                    } else if (subTaskType.intValue() == 5 && null != subTaskStatus && subTaskStatus.intValue() >= 9 && dcqyTaskCount == 1 && null != pt) {
                        percent = percent + pt.intValue();
                    } else if (subTaskType.intValue() == 5 && null != subTaskStatus && subTaskStatus.intValue() >= 9 && dcqyTaskCount > 1) {
                        dcqyTaskCount = dcqyTaskCount - 1;
                        continue;
                    } else if (null != subTaskStatus && subTaskStatus.intValue() >= 9 && null != pt) {
                        percent = percent + pt.intValue();
                    }
                }
                //因为可能删除基础任务，所以看一下是不是所有子任务都完成了，是的话就进度改成100%
                subTasks.removeIf(taskOperTask -> (null != taskOperTask.getStatus() && taskOperTask.getStatus() >= 9));
                if (subTasks.size() == 0) {
                    model.setPercent(100);
                } else {
                    model.setPercent(percent);
                }
                model.setSubTaskModelList(stms);
                model.setUserModelList(tums);
            }
            if (model.getStatus() == 1)//待安排 ，肯定没完成进度就是0
            {
                model.setPercent(0);
            }
        }

        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    public List<TaskForTeamModel> taskForTeam(Map<String, Object> params) {
        List<TaskForTeamModel> list = baseMapper.taskForTeam(params);

        //合并同类项
        Map<String, TaskForTeamModel> map = new HashMap<>();
        String teamName;
        TaskForTeamModel ttm;
        for (TaskForTeamModel model : list) {
            teamName = model.getTeamName();
            if (map.containsKey(teamName)) {
                ttm = map.get(teamName);
                if (model.getStatus().intValue() >= 9) {
                    ttm.setDoneCount(ttm.getDoneCount() + model.getTaskCount());
                } else if (model.getStatus().intValue() == 4) {
                    ttm.setUnDoneCount(ttm.getUnDoneCount() + model.getTaskCount());
                }
            } else {
                if (model.getStatus().intValue() >= 9) {
                    ttm = new TaskForTeamModel(teamName, model.getTaskCount(), 0);
                    map.put(teamName, ttm);
                } else if (model.getStatus().intValue() == 4) {
                    ttm = new TaskForTeamModel(teamName, 0, model.getTaskCount());
                    map.put(teamName, ttm);
                }
            }
        }

        list = map.values().stream().collect(Collectors.toList());
        return list;
    }

    @Override
    public List<TaskForTeamUserModel> taskForTeamUser(Map<String, Object> params) {
        Object teamId = params.get("teamId");
        if (null == teamId) {
            return Collections.EMPTY_LIST;
        }
        //获取组内人员
        List<SysUserEntity> userList = sysUserService.list(new LambdaQueryWrapper<SysUserEntity>().eq(SysUserEntity::getTeamId, teamId).select(SysUserEntity::getUserId));
        if (CollectionUtils.isEmpty(userList)) {
            return Collections.EMPTY_LIST;
        }
        List<Long> userIds = userList.stream().map(u -> u.getUserId()).collect(Collectors.toList());
        params.put("userIds", userIds);

        List<TaskForTeamUserModel> list = baseMapper.taskForTeamUser(params);

        //合并同类项
        Map<String, TaskForTeamUserModel> map = new HashMap<>();
        String userName;
        TaskForTeamUserModel ttum;
        for (TaskForTeamUserModel model : list) {
            userName = model.getUserName();
            if (map.containsKey(userName)) {
                ttum = map.get(userName);
                if (model.getStatus().intValue() == 9) {
                    ttum.setDoneCount(ttum.getDoneCount() + model.getTaskCount());
                } else if (model.getStatus().intValue() == 4) {
                    ttum.setUnDoneCount(ttum.getUnDoneCount() + model.getTaskCount());
                }
            } else {
                if (model.getStatus().intValue() == 9) {
                    ttum = new TaskForTeamUserModel(userName, model.getTaskCount(), 0);
                    map.put(userName, ttum);
                } else if (model.getStatus().intValue() == 4) {
                    ttum = new TaskForTeamUserModel(userName, 0, model.getTaskCount());
                    map.put(userName, ttum);
                }
            }
        }

        list = map.values().stream().collect(Collectors.toList());
        return list;
    }

    @Override
    public List<TaskForSelfModel> taskForSelf(Map<String, Object> params) {
        List<TaskForSelfModel> list = baseMapper.taskForSelf(params);

        //合并同类项
        Map<String, TaskForSelfModel> map = new HashMap<>();
        String planTaskName;
        TaskForSelfModel tsm;
        for (TaskForSelfModel model : list) {
            planTaskName = model.getPlanTaskName();
            if (map.containsKey(planTaskName)) {
                tsm = map.get(planTaskName);
                if (model.getStatus().intValue() == 9) {
                    tsm.setDoneCount(tsm.getDoneCount() + model.getTaskCount());
                } else if (model.getStatus().intValue() == 4) {
                    tsm.setUnDoneCount(tsm.getUnDoneCount() + model.getTaskCount());
                }
            } else {
                if (model.getStatus().intValue() == 9) {
                    tsm = new TaskForSelfModel(planTaskName, model.getTaskCount(), 0);
                    map.put(planTaskName, tsm);
                } else if (model.getStatus().intValue() == 4) {
                    tsm = new TaskForSelfModel(planTaskName, 0, model.getTaskCount());
                    map.put(planTaskName, tsm);
                }
            }
        }

        list = map.values().stream().collect(Collectors.toList());
        return list;
    }

    @Override
    public List<TaskForRankingModel> taskForRanking() {
        List<TaskForRankingModel> list = baseMapper.taskForRanking();
        return list;
    }

    @Override
    @Transactional
    public void arrangeTeam(SysUserEntity user, ArrangeTeamModel model) {
        Integer msgId = model.getMsgId();
        Integer teamId = model.getTeamId();
        if (null == msgId || null == teamId) {
            throw new RRException("参数有误");
        }
        SysUserEntity leader = sysUserService.getTeamLeader(teamId);
        if (null == leader) {
            throw new RRException("没有组长");
        }
        //消息类型变化 分配组 变为 分配人
        MsgInfo msg = msgInfoService.getById(msgId);
        if (null == msg) {
            throw new RRException("消息不存在");
        }
        String content = msg.getContent();
        ShiftsToUserModel stum = JSON.parseObject(content, ShiftsToUserModel.class);
        String type = stum.getType();
        Integer taskId = stum.getTaskId();
        //根据类型修改任务的班组 和确认人 fuck
        if ("ship".equals(type)) {
            TaskShipTask t = new TaskShipTask();
            t.setExecTeamId(teamId);
            shipTaskService.update(t, new LambdaQueryWrapper<TaskShipTask>().eq(TaskShipTask::getId, taskId));
            //管线任务不换确认人
            t.setConfirm1User(leader.getUserId().intValue());
            t.setConfirm2User(leader.getUserId().intValue());
            shipTaskService.update(t, new LambdaQueryWrapper<TaskShipTask>().eq(TaskShipTask::getId, taskId).ne(TaskShipTask::getType, 1));
        } else if ("pot".equals(type)) {
            TaskPotTask t = new TaskPotTask();
            t.setExecTeamId(teamId);
            potTaskService.update(t, new LambdaQueryWrapper<TaskPotTask>().eq(TaskPotTask::getId, taskId));
            //管线任务不换确认人
            t.setConfirm1User(leader.getUserId().intValue());
            t.setConfirm2User(leader.getUserId().intValue());
            potTaskService.update(t, new LambdaQueryWrapper<TaskPotTask>().eq(TaskPotTask::getId, taskId).ne(TaskPotTask::getType, 1));
        } else if ("oper".equals(type)) {
            TaskOperTask t = new TaskOperTask();
            t.setExecTeamId(teamId);
            t.setConfirmUser(leader.getUserId().intValue());
            operTaskService.update(t, new LambdaQueryWrapper<TaskOperTask>().eq(TaskOperTask::getId, taskId));
        } else if ("service".equals(type)) {
            TaskServiceTask t = new TaskServiceTask();
            t.setExecTeamId(teamId);
            t.setConfirmUser(leader.getUserId().intValue());
            serviceTaskService.update(t, new LambdaQueryWrapper<TaskServiceTask>().eq(TaskServiceTask::getId, taskId));
        }

        msg.setType("计划任务-分配人员");
        msgInfoService.updateById(msg);

        MsgUser mu = new MsgUser();
        mu.setUserId(leader.getUserId().intValue());
        msgUserService.update(mu, new LambdaQueryWrapper<MsgUser>().eq(MsgUser::getMsgId, msgId));//消息换主人

    }

    @Override
    @Transactional
    public void arrangeUser(SysUserEntity user, ArrangeUserModel model) {
        Integer msgId = model.getMsgId();
        Integer targetUserId = model.getTargetUserId();
        Integer taskId = model.getTaskId();
        String type = model.getType();
        String targetUserName = model.getTargetUserName();

        if ("ship".equals(type)) {
            TaskShipTask t = new TaskShipTask();
            t.setUserMainId(targetUserId);
            shipTaskService.update(t, new LambdaQueryWrapper<TaskShipTask>().eq(TaskShipTask::getId, taskId));
            taskExecutor.submit(() -> {
                TaskShipTaskUser tus = new TaskShipTaskUser(taskId, targetUserId, targetUserName, null, null);
                shipTaskUserService.save(tus);//保存人员交接记录
            });
        } else if ("pot".equals(type)) {
            TaskPotTask t = new TaskPotTask();
            t.setUserMainId(targetUserId);
            potTaskService.update(t, new LambdaQueryWrapper<TaskPotTask>().eq(TaskPotTask::getId, taskId));
            taskExecutor.submit(() -> {
                TaskPotTaskUser tus = new TaskPotTaskUser(taskId, targetUserId, targetUserName, null, null);
                potTaskUserService.save(tus);//保存人员交接记录
            });
        } else if ("oper".equals(type)) {
            TaskOperTask t = new TaskOperTask();
            t.setUserMainId(targetUserId);
            operTaskService.update(t, new LambdaQueryWrapper<TaskOperTask>().eq(TaskOperTask::getId, taskId));
            taskExecutor.submit(() -> {
                TaskOperTaskUser tus = new TaskOperTaskUser(taskId, targetUserId, targetUserName, null, null);
                operTaskUserService.save(tus);//保存人员交接记录
            });
        } else if ("service".equals(type)) {
            TaskServiceTask t = new TaskServiceTask();
            t.setUserMainId(targetUserId);
            serviceTaskService.update(t, new LambdaQueryWrapper<TaskServiceTask>().eq(TaskServiceTask::getId, taskId));
            taskExecutor.submit(() -> {
                TaskServiceTaskUser tus = new TaskServiceTaskUser(taskId, targetUserId, targetUserName, null, null);
                serviceTaskUserService.save(tus);//保存人员交接记录
            });
        } else {
            throw new RRException("任务类型参数有误");
        }
        taskExecutor.submit(() -> {
            //消息改造 换人
            MsgInfo msg = msgInfoService.getById(msgId);
            String content = msg.getContent();
            if (StringUtils.isNotEmpty(content)) {
                ShiftsToUserModel shiftsToUserModel = JSON.parseObject(content, ShiftsToUserModel.class);
                ShiftsModel sm = new ShiftsModel();
                sm.setDetail(shiftsToUserModel.getDetail());
                sm.setSelfUser(shiftsToUserModel.getSelfUser());
                sm.setTargetUser(targetUserName);
                List<Integer> userIds = new ArrayList<>();
                userIds.add(targetUserId);
                msg.setType("计划任务");
                msg.setContent(JSON.toJSONString(sm));
                msgInfoService.updateById(msg);//消息改造保存
                //换人 并设置未读
                MsgUser nu = new MsgUser();
                nu.setUserId(targetUserId);
                nu.setStatus(0);
                msgUserService.update(nu, new LambdaQueryWrapper<MsgUser>().eq(MsgUser::getMsgId, msgId));
            }
        });
    }

    @Override
    public int assistTaskCount(SysUserEntity user) {
        Integer userId = user.getUserId().intValue();
        int count = baseMapper.assistTaskCount(userId);
        return count;
    }

    @Override
    public List<TaskAllModel> assistTaskList(SysUserEntity user) {
        Integer userId = user.getUserId().intValue();//先只查自己的任务，其他业务后面再说呗
        List<TaskAllModel> list = baseMapper.assistTaskList(userId);
//        list.forEach(taskAllModel -> {
//            if (StringUtils.isNotEmpty(taskAllModel.getUserAssist())) {
//                taskAllModel.setUserAssistModelList(JSON.parseArray(taskAllModel.getUserAssist(), WorkUserModel.class));
//            }
//        });
        return list;
    }

//    public static void main(String[] args) {
//        Map<String, Integer> map = new HashMap<>();
//        map.put("11", 1);
//        map.put("5", 5);
//        map.put("46", 6);
//        map.put("e3", 3);
//        map.put("20", 2);
//        map.put("r4", 4);
//        Map<String, Integer> result = new LinkedHashMap<>();
//        Stream<Map.Entry<String, Integer>> st = map.entrySet().stream();
//
//        st.sorted(Comparator.comparing(e -> e.getValue())).forEach(e -> result.put(e.getKey(), e.getValue()));
//
//        System.out.println(result.size());
//    }

}
